package web

import (
	"encoding/json"
	"time"

	"gitee.com/xgotool/sqlite-logs-more/service/logs"
	"gitee.com/xiaoyutab/xgotool/xgin"
	"gitee.com/xiaoyutab/xgotool/xstring"
	"github.com/gin-gonic/gin"
)

// 搜索日志信息【根据日志中的关键词和日期进行搜索】
func SearchLog(c *gin.Context) *xgin.Response {
	type temp_struct struct {
		SearchTimes []string    `json:"search_times" form:"search_times" xml:"search_times"` // 时间范围[0]开始时间[1]结束时间
		DerviceId   json.Number `json:"dervice_id" form:"dervice_id" xml:"dervice_id"`       // 设备ID
		Args        string      `json:"args" form:"args" xml:"args"`                         // 应用ID
		Keys        string      `json:"keys" form:"keys" xml:"keys"`                         // 搜索关键词
	}
	type temp_struct_used struct {
		SearchTimes []string `json:"search_times" form:"search_times" xml:"search_times"`
		DerviceId   int64    `json:"dervice_id" form:"dervice_id" xml:"dervice_id"`
		Args        string   `json:"args" form:"args" xml:"args"`
		Keys        string   `json:"keys" form:"keys" xml:"keys"`
	}
	temp := temp_struct{}
	if err := xgin.Bind(c, &temp); err != nil {
		return xgin.Resp().Error(err)
	}
	// 正式变量赋值
	// 请使用param进行参数验证、变量效验等操作
	param := temp_struct_used{}
	param.SearchTimes = temp.SearchTimes
	param.DerviceId = xstring.JInt64(temp.DerviceId)
	param.Args = temp.Args
	param.Keys = temp.Keys
	if len(param.SearchTimes) != 2 {
		param.SearchTimes = []string{
			time.Now().AddDate(0, 0, -7).Format(time.DateOnly),
			time.Now().Format(time.DateOnly),
		}
	}

	lis, err := logs.AllLogSearch(param.SearchTimes[0], param.SearchTimes[1], param.DerviceId, param.Args, param.Keys)
	if err != nil {
		return xgin.Resp().Error(err)
	}
	return xgin.Resp().NoPage(c, lis, len(lis))
}
